package com.accounting.client.frontend.product.handlers;

import java.util.ArrayList;
import java.util.List;

import com.accounting.client.frontend.packages.AddPackageHandler;
import com.accounting.client.frontend.packages.PackageDetailHandler;
import com.accounting.client.remote.Services;
import com.accounting.client.remote.enumeration.Courier;
import com.accounting.client.remote.enumeration.PackageStatus;
import com.accounting.client.remote.enumeration.PackageType;
import com.accounting.client.remote.obj.PackageInfo;
import com.accounting.client.remote.obj.PurchaseRecord;
import com.accounting.client.resource.BoxResources;
import com.accounting.client.session.ErrorHandler;
import com.accounting.client.session.SessionManager;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.dom.client.Style;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HasAlignment;
import com.google.gwt.user.client.ui.Widget;

import corelib.client.date.DateFormats;
import corelib.client.delegate.Action;
import corelib.client.resource.CommonResources;
import corelib.client.schedule.DeferredTask;
import corelib.client.ui.SimpleMask;
import corelib.client.ui.widget.SimpleDataModel;
import corelib.client.ui.widget.WidgetListener;
import corelib.client.ui.widget.dialog.SimpleDialog;
import corelib.client.ui.widget.dialog.SimpleLargeDialogHandler;
import corelib.client.ui.widget.form.SimpleLabel;
import corelib.client.ui.widget.grid.SimpleDataGrid;
import corelib.client.ui.widget.grid.SimpleDataGridHandler;
import corelib.client.ui.widget.grid.cell.CellRenderer;
import corelib.client.ui.widget.grid.column.ColumnConfig;
import corelib.client.ui.widget.grid.column.ColumnConfigs;
import corelib.client.ui.widget.panel.SimpleLayoutPanel;
import corelib.client.ui.widget.toolbar.SimpleRibbon;
import corelib.client.ui.widget.toolbar.SimpleRibbonButton;
import corelib.client.ui.widget.toolbar.SimpleRibbonButton.ButtonSize;

public class PurchaseRecordPackageHandler extends SimpleLargeDialogHandler {
	
	private PurchaseRecord purchaseRecord;
	private SimpleRibbon toolBar;
	
	private SimpleDataGrid<PackageInfo> packageTrackTable;
	private ProductStockPackageTableHandler packageTableHandler;
	
	public PurchaseRecordPackageHandler(PurchaseRecord info){
		this.purchaseRecord = info;
	}
	
	private SimpleDataGrid<PackageInfo> createTable(){
		return new SimpleDataGrid<PackageInfo>(
			   20,
			   packageTableHandler = new ProductStockPackageTableHandler()
		);
	}
	@Override
	public Widget getContentPanel() {
		toolBar = createToolBar();
		packageTrackTable = createTable();
		
		SimpleLayoutPanel layout = new SimpleLayoutPanel();
		layout.add(toolBar);
		layout.add(packageTrackTable);
		layout.setWidgetTopHeight(toolBar, 0, Unit.PX, 80, Unit.PX);
		layout.setWidgetTopBottom(packageTrackTable, 80, Unit.PX, 0, Unit.PX);
		return layout;
	}
	
	private SimpleRibbon createToolBar(){
		SimpleRibbon toolBar = new SimpleRibbon();
		toolBar.addPushButton(new SimpleRibbonButton("关闭", 
				CommonResources.INSTANCE.close32(),
				ButtonSize.Medium,
				new WidgetListener(){
					@Override
					public void valueUpdated(Widget widget) {
						closeDialog();
					}
				}
		),Style.Float.RIGHT);
		toolBar.addPushButton(new SimpleRibbonButton("增加新包裹", 
				CommonResources.INSTANCE.plus1_32(),
				ButtonSize.Medium,
				new WidgetListener(){
					@Override
					public void valueUpdated(Widget widget) {
						SimpleDialog.show(new AddPackageHandler(purchaseRecord.getId(), new Action(){
							@Override
							public void run() {
								search();
							}
						}));
					}
				}
		));
		toolBar.addPushButton(new SimpleRibbonButton("查询", 
				BoxResources.INSTANCE.track32(),
				ButtonSize.Medium,
				new WidgetListener(){
					@Override
					public void valueUpdated(Widget widget) {
						PackageInfo info = packageTrackTable.getSelectedObject();
						if (info != null){
							SimpleDialog.show(new PackageDetailHandler(info));
						}
					}
				}
		));
		toolBar.addPushButton(new SimpleRibbonButton("刷新", 
				CommonResources.INSTANCE.refresh32(),
				ButtonSize.Medium,
				new WidgetListener(){
					@Override
					public void valueUpdated(Widget widget) {
						search();
					}
				}
		));
		return toolBar;
	}
	
	@Override
	public void onShowing() {
		super.onShowing();
		new DeferredTask().run(new ScheduledCommand(){
			@Override
			public void execute() {
				search();
			}
		}, 400);
	}
	
	private void search() {
		SimpleMask.show(packageTrackTable, "努力加载中...");
		String passport = SessionManager.getPassport();
		Services.PackageService.ListPackagesByReference(passport, purchaseRecord.getId(), new AsyncCallback<List<PackageInfo>>(){
			@Override
			public void onFailure(Throwable caught) {
				SimpleMask.hide(packageTrackTable);
				ErrorHandler.handleServiceError(caught);
			}
			@Override
			public void onSuccess(List<PackageInfo> result) {
				SimpleMask.hide(packageTrackTable);
				packageTableHandler.setObjects(result);
			}
		});
	}
	
	private class ProductStockPackageTableHandler extends SimpleDataGridHandler<PackageInfo> {
		
		private final static String TrackingId   	= "TrackingId";
		private final static String Type 			= "Type";
		private final static String CourierId		= "CourierId";
		private final static String Status 			= "Status";
		private final static String Recipient   	= "Recipient";
		private final static String Description 	= "Description";
		private final static String ShippingAddress = "PostAddress";
		private final static String DateCreated 	= "DateCreated"; 
		
		List<PackageInfo> Data;
		
		@Override
		public List<ColumnConfig> createColumns() {
			List<ColumnConfig> configs = new ArrayList<ColumnConfig>();
			configs.add(ColumnConfigs.create(DateCreated, 	  "创建日期",  100,  HasAlignment.ALIGN_LEFT, DateFormats.DD_MM_YYYY));
			configs.add(ColumnConfigs.create(CourierId,    	  "快递",     100,   new CourierCellRenderer()));
			configs.add(ColumnConfigs.create(TrackingId,   	  "快递单号", 	 100,   new TrackingIDCellRender()));
			configs.add(ColumnConfigs.create(Type,   	  	  "包裹类型", 	 100));
			configs.add(ColumnConfigs.create(Status,    	  "快递状态",   100,  new StatusCellRender()));
			configs.add(ColumnConfigs.create(Recipient,   	  "收件人",    100,  new CustomerCellRender()));
			configs.add(ColumnConfigs.create(Description, 	  "包裹描述",   200,  new DescriptionCellRender()));
			configs.add(ColumnConfigs.create(ShippingAddress, "收件人地址", 200,   new PostalAddressRender()));
			return configs;
		}

		@Override
		public void format(int index, SimpleDataModel<PackageInfo> model) {
			PackageInfo obj = model.getObject();
			model.set(TrackingId,      obj.getTrackingId());
			model.set(CourierId,       obj.getCourierId());
			model.set(Status,    	   obj.getStatus());
			model.set(Type,    	   	   PackageType.getPackageType(obj.getType()).getCName());
			model.set(Recipient,   	   obj.getRecipient());
			model.set(Description,     obj.getDescription());
			model.set(ShippingAddress, obj.getShippingAddress());
			model.set(DateCreated, 	   obj.getDateCreated());
		}
		
		public void setObjects(List<PackageInfo> objects){
			this.Data = objects;
			this.getGrid().setObjects(objects);
		}
		
		@Override
		public List<PackageInfo> getObjects() {
			return this.Data;
		}

		@Override
		public void onObjectClicked(PackageInfo obj) {
			if (obj != null){
				
			}
		}

		@Override
		public void onObjectDoubleClicked(PackageInfo obj) {
			onObjectClicked(obj);	
		}
		
		private class StatusCellRender extends CellRenderer<PackageInfo>{

			@Override
			public void render(SimpleDataModel<PackageInfo> model,
					ColumnConfig columnConfig, int rowIndex, int colIndex,
					SafeHtmlBuilder sb) {
				int status = model.getObject().getStatus();
				if (status == PackageStatus.Delivered){
					sb.append(SimpleLabel.createSuccess("已投递").asSafeHtml());	
				}
				else if (status == PackageStatus.Pending){
					sb.append(SimpleLabel.createWarnning("未处理").asSafeHtml());
				}
				else if (status == PackageStatus.Shipping){
					sb.append(SimpleLabel.createPrimary("运输中").asSafeHtml());
				}
				else if (status == PackageStatus.Failed){
					sb.append(SimpleLabel.createDanger("失败").asSafeHtml());
				}
				else if (status == PackageStatus.Cancelled){
					sb.append(SimpleLabel.createDanger("取消").asSafeHtml());
				}
				else {
					sb.append(SimpleLabel.createInfo(PackageStatus.getName(status)).asSafeHtml());
				}
			}
			
		}
		
		private class TrackingIDCellRender extends CellRenderer<PackageInfo> {
			@Override
			public void render(SimpleDataModel<PackageInfo> model,
							   ColumnConfig columnConfig, 
							   int rowIndex, 
							   int colIndex,
							   SafeHtmlBuilder sb) {
				sb.appendHtmlConstant("<div style='padding: 5px; font-weight:bold; font-size:13px;'>")
				  .appendHtmlConstant(model.getObject().getTrackingId())
				  .appendHtmlConstant("</div>");
			}
		}
		
		private class CustomerCellRender extends CellRenderer<PackageInfo> {
			@Override
			public void render(SimpleDataModel<PackageInfo> model,
							   ColumnConfig columnConfig, 
							   int rowIndex, 
							   int colIndex,
							   SafeHtmlBuilder sb) {
				sb.appendHtmlConstant("<div style='padding: 5px; font-weight:bold; font-size:13px;'>")
				  .appendHtmlConstant(model.getObject().getRecipient())
				  .appendHtmlConstant("</div>");
			}
		}
		
		private class CourierCellRenderer extends CellRenderer<PackageInfo> {
			@Override
			public void render(SimpleDataModel<PackageInfo> model,
							   ColumnConfig columnConfig, 
							   int rowIndex, 
							   int colIndex,
							   SafeHtmlBuilder sb) {
				int poster = model.getObject().getCourierId();
				sb.appendHtmlConstant("<div style='padding: 5px; font-weight: bold;'>")
				  .append(Courier.GetImageAsHtml(poster))
				  .appendHtmlConstant("</div>");
			}
		}
		
		private class DescriptionCellRender extends CellRenderer<PackageInfo> {
			@Override
			public void render(SimpleDataModel<PackageInfo> model, 
							   ColumnConfig columnConfig, 
							   int rowIndex, 
							   int colIndex,
							   SafeHtmlBuilder sb) {
				
				String description = model.getObject().getDescription();
				sb.appendHtmlConstant("<span style='padding: 3px; font-size:13px; font-weight: bold;'>")
				  .appendHtmlConstant(description)
				  .appendHtmlConstant("</span>");
			}
		}
		
		private class PostalAddressRender extends CellRenderer<PackageInfo> {
			@Override
			public void render(SimpleDataModel<PackageInfo> model,
							   ColumnConfig columnConfig, 
							   int rowIndex, 
							   int colIndex,
							   SafeHtmlBuilder sb) {
				String address = model.getObject().getShippingAddress();
				sb.appendHtmlConstant("<span style='padding: 3px; font-size:13px; font-weight: bold;'>")
				  .appendHtmlConstant(address)
				  .appendHtmlConstant("</span>");
			}
		}
		
	}
}

